package cn.xorange.commons.security.handler;

import cn.xorange.commons.security.constants.HeaderConstants;
import cn.xorange.commons.security.constants.SecurityConstants;
import cn.xorange.commons.security.entity.ClaimsInfo;
import cn.xorange.commons.security.utils.JwtUtils;
import cn.xorange.commons.security.utils.SecurityUtils;
import cn.xorange.commons.utils.cache.ICacheService;
import cn.xorange.commons.utils.configuration.constants.HttpStatus;
import cn.xorange.commons.utils.http.ServletUtils;
import cn.xorange.commons.utils.lang.ObjectUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author : yangjian
 * @date : 2023/11/28
 */
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Resource
    ICacheService cacheService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        try {
            String jwtToken = JwtUtils.getJwtToken(request, response);

            if(Objects.nonNull(jwtToken)) {
                String sysType = JwtUtils.getAudience(jwtToken);

                if (Objects.nonNull(sysType)) {
                    ClaimsInfo claimsInfo = JwtUtils.getClaims(jwtToken);
                    request.setAttribute(SecurityConstants.TOKEN_ID, claimsInfo.getTokenId());
                    cacheService.delete(claimsInfo.tokenKey());
                }
            }
        }catch (Exception e){
            // ignore
        }
        SecurityContextHolder.clearContext();
        ServletUtils.responseSuccessOut(response, "退出成功");
    }
}
